package com.family.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.family.common.core.domain.entity.SysRole;
import com.family.common.core.domain.entity.SysUser;
import com.family.common.exception.ServiceException;
import com.family.system.mapper.SysRoleMapper;
import com.family.system.mapper.SysUserMapper;
import com.family.system.mapper.SysUserPostMapper;
import com.family.system.mapper.SysUserRoleMapper;
import com.family.system.service.ISysUserService;
import com.family.system.service.IUserManagerService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
public class UserManagerServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements IUserManagerService {
    private SysRoleMapper sysRoleMapper;

    private SysUserRoleMapper userRoleMapper;
    private SysUserPostMapper userPostMapper;
    private ISysUserService iSysUserService;

    @Override
    public List<SysUser> selectSysUserList(SysUser sysUser) {
        return baseMapper.selectSysUserList(sysUser);
    }

    @Override
    public SysUser selectSysUserByUserId(Long userId) {
        return this.getById(userId);
    }

    @Override
    public boolean insertSysUser(SysUser sysUser) {

        String userName = sysUser.getTenantFlag() + sysUser.getUserName();
        //判断用户名是否存在
        SysUser one = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName, userName).last("LIMIT 1"));
        if(Objects.nonNull(one)){
            throw new ServiceException("用户名称重复");
        }

        Long roleId = this.getRoleId(sysUser.getTenantFlag());
        sysUser.setRoleId(roleId);
        sysUser.setUserName(userName);
        return this.save(sysUser);
    }

    @Override
    public int updateSysUser(SysUser sysUser) {
        return iSysUserService.updateUser(sysUser);
    }

    @Override
    public int deleteSysUserByUserIds(Long[] userIds) {
        return iSysUserService.deleteUserByIds(userIds);
    }


    private Long getRoleId(String tenantFlag){
        List<SysRole> sysRoleList = sysRoleMapper.selectRoleByRoleKey(tenantFlag);
        if(CollUtil.isEmpty(sysRoleList)){
            throw new ServiceException("处理失败,请联系管理员进行处理");
        }
        if(sysRoleList.size() > 1){
            throw new ServiceException("处理失败,请联系管理员进行处理");
        }
        return sysRoleList.get(sysRoleList.size() - 1).getRoleId();
    }

}
